<template>
	<PageWrapper contentFullHeight fixedHeight>
		<BasicTable @register="registerTable" @fetch-success="onFetchSuccess">
			<template #toolbar>
				<a-button type="primary" @click="handleCreate"> 新增菜单 </a-button>
			</template>
			<template #bodyCell="{ column, record }">
				<template v-if="column.key === 'action'">
					<TableAction
						:actions="[
							{
								icon: 'clarity:note-edit-line',
								onClick: handleEdit.bind(null, record),
							},
							{
								icon: 'ant-design:delete-outlined',
								color: 'error',
								popConfirm: {
									title: '是否确认删除',
									placement: 'left',
									confirm: handleDelete.bind(null, record),
								},
							},
						]"
					/>
				</template>
			</template>
		</BasicTable>
		<MenuDrawer @register="registerDrawer" @success="handleSuccess" />
	</PageWrapper>
</template>
<script lang="ts">
import { defineComponent, nextTick } from 'vue';

import { BasicTable, TableAction, PageWrapper } from '#/components';

import { useDrawer, useTable } from '#/hooks';
import MenuDrawer from './MenuDrawer.vue';

import { columns, searchFormSchema } from './menu.data';
import { deleteBackMenu, getAllMenuTree, getBackMenuById } from '@/api/sys/menu';
import { useMessage } from '@/hooks/web/useMessage';

export default defineComponent({
	name: 'MenuManagement',
	components: { BasicTable, MenuDrawer, TableAction, PageWrapper },
	setup() {
		const { createMessage } = useMessage();

		const [registerDrawer, { openDrawer }] = useDrawer();
		const [registerTable, { reload, expandAll }] = useTable({
			title: '菜单列表',
			api: getAllMenuTree,
			columns,
			formConfig: {
				rowProps: { justify: 'start' },
				labelWidth: 120,
				schemas: searchFormSchema,
			},
			isTreeTable: true,
			pagination: false,
			striped: false,
			useSearchForm: true,
			showTableSetting: true,
			showIndexColumn: false,
			canResize: false,
			actionColumn: {
				width: 120,
				title: '操作',
				dataIndex: 'action',
			},
		});

		function handleCreate() {
			openDrawer(true, {
				isUpdate: false,
			});
		}

		async function handleEdit(record: Recordable) {
			if (record.parentId == 0) {
				record.parentId = null;
			} else {
				const parentMenu: any = await getBackMenuById(record.parentId);
				record.parentName = parentMenu.meta.title;
			}
			openDrawer(true, {
				record,
				isUpdate: true,
			});
		}

		function handleDelete(record: Recordable) {
			deleteBackMenu(record.menuId).then(
				() => {
					createMessage.success('删除成功');
					reload();
				},
				err => {
					createMessage.error(err);
				},
			);
		}

		function handleSuccess() {
			reload();
		}

		function onFetchSuccess() {
			// 演示默认展开所有表项
			nextTick(expandAll);
		}

		return {
			registerTable,
			registerDrawer,
			handleCreate,
			handleEdit,
			handleDelete,
			handleSuccess,
			onFetchSuccess,
		};
	},
});
</script>
